/*
 * Created on Jan 25, 2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.broadvision.manage.common.tools.action.common;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.broadvision.data.client.Category;
import com.broadvision.data.client.Content;
import com.broadvision.data.client.DataManager;
import com.broadvision.data.common.TableData;
import com.broadvision.data.common.RowData;
import com.broadvision.data.common.CallSettings;
import com.broadvision.data.common.ContentUID;
import com.broadvision.data.common.DataConstants;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.manage.tools.ToolsLog;

/**
 * @author kwlee
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class CategorizedCntPickerPopupAction extends BasePickerPopupAction {

  public static String CATEGORYINFO_BEAN_NAME="mtCategoryInfoView";
  public static String SUBCATEGORY_BEAN_NAME="mtCntPickerSubcategoryDTO";
  public static String PATH_DTO_BEAN_NAME="mtPathDTO";
  
  public static String INVALID_CURRENT_CAT_ID = "mt.picker.popup.error.no.valid.current.cat.id";
  
  private Category currentCategory = null;  // This variable is used a place holder
                                            // to store the current category 
                                            // in this request. We need to set 
                                            // it back to null after using it.
  
  /* (non-Javadoc)
   * @see com.broadvision.portal.tools.action.BaseAction#processExecute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  protected ActionForward doProcessExecute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
      
      DynaActionForm pickerPopupForm = (DynaActionForm)form;
      if (pickerPopupForm == null || mapping == null) {
        request.setAttribute(Globals.ERROR_KEY, "error.application");
        return mapping.findForward("failure");
      }
      
      // initialize category info bean
      ViewDynaBean catInfo = new ViewDynaBean(CATEGORYINFO_BEAN_NAME, mapping);
      request.setAttribute(CATEGORYINFO_BEAN_NAME, catInfo);

      try {
//        ProcessSubprocessPath path = ProcessSubprocessPath.getInstance(mapping, request, serviceId);
//        path.updatePath(0);
        DataManager dm = new DataManager();
        CallSettings callsettings = dm.getCallSettings();
        callsettings.setFilteringFlag(false);

        int cntOid = Integer.parseInt((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));
        String contentTypeName = DataManager.getContentTypeName(cntOid);
//        ProcessCategory processCategory = new ProcessCategory(serviceId);
//        boolean viewCategory = visitor.isActionPermitted(processCategory, "View");
          boolean viewCategory = true;
//        PropertyUtils.setSimpleProperty(view, "viewCategory", new Boolean(viewCategory));
//        boolean editCategory = visitor.isActionPermitted(processCategory, "Edit");
//        PropertyUtils.setSimpleProperty(view, "editCategory", new Boolean(editCategory));
//        boolean createCategory = visitor.isActionPermitted(processCategory, "Create");
//        PropertyUtils.setSimpleProperty(view, "createCategory", new Boolean(createCategory));
//        boolean deleteCategory = visitor.isActionPermitted(processCategory, "Delete");
//        PropertyUtils.setSimpleProperty(view, "deleteCategory", new Boolean(deleteCategory));
//        PropertyUtils.setSimpleProperty(view, "editOrDeleteCategory", new Boolean(editCategory || deleteCategory));
        if (viewCategory == false) {
          PropertyUtils.setSimpleProperty(catInfo, "subcategories", null);
          PropertyUtils.setSimpleProperty(catInfo, "paths", null);
          return mapping.findForward("success");
        }
        
        List childCategories = null;
        Category oneCategory = null;
        long catOid = ((Long)PropertyUtils.getSimpleProperty(pickerPopupForm, "currentCategoryOid")).longValue();
        
        // Check if the current category id is 0, which is root
        // If current cat is not 0, create a category represents the category id. Then get
        // the subcategories.
        if (catOid != 0) {
          ContentUID catUid = new ContentUID(DataConstants.DEFAULT_CATEGORY_TYPE_ID, 
                                              getServiceId(request), catOid, 
                                              contentTypeName);
          if (dm.categoryExists(catUid) == false) {
            // If not a valid category id, use the default root category
            childCategories = dm.getTopCategories(DataConstants.DEFAULT_CATEGORY_TYPE_ID,
                                                  getServiceId(request), cntOid);
            // Also set the catOid to 0
            catOid = 0;
            PropertyUtils.setSimpleProperty(pickerPopupForm, "currentCategoryOid", new Long(0));
            System.out.println(getMessage(request, INVALID_CURRENT_CAT_ID));
          }
          else {
            oneCategory = dm.getCategory(catUid);
            // Save the current category
            currentCategory = oneCategory;
            // Set the current category name if it's not the root category
            PropertyUtils.setSimpleProperty(pickerPopupForm, "currentCategoryName", 
                                oneCategory.getStringValue(NAME));
            childCategories = oneCategory.getChildren();
          }// else
        }// if
        // If current cat is 0, get top categories
        else {
          childCategories = dm.getTopCategories(DataConstants.DEFAULT_CATEGORY_TYPE_ID,
                                                    getServiceId(request), cntOid);
        }// else
        
        // Take care of the subcategories
        childCategories = doCatListFiltering(mapping, form, request, response, childCategories);
        int count = (childCategories == null ? 0 : childCategories.size());
        if (count > 0) {
          ArrayList childCategoriesArray = new ArrayList(count);
          for (int i = 0; i < count; i++) {
            ViewDynaBean oneSubDto = new ViewDynaBean(SUBCATEGORY_BEAN_NAME, mapping);
            Category oneChildCategory = null;
            Object item = childCategories.get(i);
            if (item instanceof PickerFilterHelper) {
              PickerFilterHelper helper = (PickerFilterHelper)item;
              if (helper.getContent() instanceof Category) {
                PropertyUtils.setSimpleProperty(oneSubDto, "canSelect", new Boolean(helper.isCanSelect()));
                oneChildCategory = (Category)helper.getContent();
              }// if
              else {
                continue;
              }// else
            }// if
            else if (item instanceof Category) {
              oneChildCategory = (Category)item;
            }// else if
            else {
              continue;
            }// else
            PropertyUtils.setSimpleProperty(oneSubDto, "oid", new Long(oneChildCategory.getOid()));
            PropertyUtils.setSimpleProperty(oneSubDto, "name", 
                                    oneChildCategory.getStringValue(NAME));
            PropertyUtils.setSimpleProperty(oneSubDto, "nameToSave", 
                                    oneChildCategory.getPathName());
            childCategoriesArray.add(oneSubDto);
          }// for
          PropertyUtils.setSimpleProperty(catInfo, "subcategories", childCategoriesArray);
        }
        else {
          PropertyUtils.setSimpleProperty(catInfo, "subcategories", null);
        }
                
        // Take care of the paths
        // If current cat is not 0, figure out the paths
        if (catOid != 0) {
          // paths exclude "/"
          ArrayList pathArray = new ArrayList();
          while (oneCategory != null) {
            ViewDynaBean onePathDto = new ViewDynaBean(PATH_DTO_BEAN_NAME, mapping);
            PropertyUtils.setSimpleProperty(onePathDto, "oid", new Long(oneCategory.getOid()));
            PropertyUtils.setSimpleProperty(onePathDto, "name", 
                                            oneCategory.getStringValue(NAME));
            if (catOid == oneCategory.getOid()) {
              PropertyUtils.setSimpleProperty(onePathDto, "isCurrentPath", new Boolean(true));
            }
            else {
              PropertyUtils.setSimpleProperty(onePathDto, "isCurrentPath", new Boolean(false));
            }
            pathArray.add(0, onePathDto); // insert to the beginning of the array
            oneCategory = oneCategory.getParent();
          }
          PropertyUtils.setSimpleProperty(catInfo, "paths", pathArray);
        }// if
        // If current cat is 0, set path to null
        else {
          PropertyUtils.setSimpleProperty(catInfo, "paths", null);
        }// else
      }
      catch (Exception ex) {
        request.setAttribute(Globals.ERROR_KEY, "error.application");
        return mapping.findForward("failure");
      }
    return super.doProcessExecute(mapping, form, request, response);
  }

  /* (non-Javadoc)
   * @see com.broadvision.portal.tools.util.BasePickerPopupAction#getList(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public List getList(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    
    List list = new ArrayList();
    if (currentCategory != null) {
      DynaActionForm pickerPopupForm = (DynaActionForm)form;
      int cntTypeId = Integer.parseInt((String)PropertyUtils.getSimpleProperty(pickerPopupForm, "contentTypeId"));
      list = currentCategory.getMemberContents(null, null, cntTypeId, false);     

       // 45113, 45110, 45105: back out 44966 fix for BVMC
       /*
       DataManager dm = new DataManager();
       String query = "SELECT A.OID, A.NAME, A.PROD_ID from BV_PRODUCT A, BV_CONTENT_REF B WHERE  ( A.OID=B.OID AND B.PARENT_OID=";
       query += currentCategory.getOid();
       query += " AND A.DELETED=0 )";
       
       TableData result = dm.getDataByQuery(null, query);
       if(result != null && result.size() > 0) {
       
          for(int i=0; i < result.size(); i++ ) {
          
            RowData row = result.getRow(i);
            Content cnt = new Content(cntTypeId, getServiceId(request));
            cnt.setData(row);
            list.add(cnt);
          }
        }*/
       
      // Make sure to reset the currentCategory to null after using it
      currentCategory = null;
    }// if
    return list;
  }

  /* (non-Javadoc)
   * @see com.broadvision.portal.tools.util.BasePickerPopupAction#getTabPageIndex()
   */
  public int getTabPageIndex() {
    return 0;
  }

}
